import React, {Component} from 'react';
import {Upload, Icon, Modal, message} from 'antd';

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

/**
 * 上传组件
 * @param fileList 图片列表
 * @param maxSize 最多上传数
 * @param viewName 组件名称
 * @param onChange 每次上传成功回调
 */
export default class UpdateImg extends Component {

    state = {
        previewVisible: false,
        previewImage: '',
        fileList: [],
    };

    componentWillMount() {

        if (this.props && this.props.fileList) {
            let index = 0;
            for (let item of this.props.fileList) {
                this.state.fileList.push({
                    uid: index,
                    url: item,
                    status: 'done',
                    name: item
                });
                index++;
            }
        }
    }


    /**
     * 关闭查看大图
     */
    handleCancel = () => this.setState({previewVisible: false});


    /**
     * 点击查看大图
     * @param file
     * @returns {Promise<void>}
     */
    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
        });
    };


    /**
     * 上传回调
     * @param res
     */
    handleChange = (res) => {

        // 处理图片的上传成功与失败
        if (res.file.status === 'done' && res.file.response) {
            if (res.file.response.success === true) {
                for (let item of res.fileList) {
                    if (item.uid === res.file.uid) {
                        item.url = res.file.response.data;
                    }
                }
            }

            // 失败，则不添加这条数据
            else {
                let fileList = [];
                for (let item of res.fileList) {
                    if (item.uid !== res.file.uid) {
                        fileList.push(item);
                    }
                }
                res.fileList = fileList;
                message.error('上传失败，请重试');
            }

            this.props.onChange(res);
        }

        this.setState({
            fileList: res.fileList
        })
    };


    /**
     * 图片删除
     * @param res
     */
    handleRemove = (res) => {
        if (res && res.status === 'removed') {

            let fileList = [];
            for (let item of this.state.fileList) {
                if (item.url !== res.url) {
                    fileList.push(item);
                }
            }

            this.props.onChange({
                file: res,
                fileList: fileList
            });
        }
    };


    render() {

        const {previewVisible, previewImage, fileList} = this.state;
        let {maxSize, viewName} = this.props;

        // 设置默认值
        if (!maxSize) maxSize = 3;
        if (!viewName) viewName = 'Upload';


        const uploadButton = (
            <div>
                <Icon type="plus"/>
                <div className="ant-upload-text">{viewName}</div>
            </div>
        );
        return (
            <div className="clearfix">
                <Upload
                    // action="https://songjiuyihao.com/oss/upload.json"
                    action={'https://songjiuyihao.com/oss/upload.json'}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                    onRemove={this.handleRemove}
                >
                    {fileList.length >= maxSize ? null : uploadButton}
                </Upload>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{width: '100%'}} src={previewImage}/>
                </Modal>
            </div>
        );
    }
}
